package model

import (
	"errors"
	"liu_yu/config"
	"liu_yu/handler/request"

	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(30)" json:"username"`
	Password string `gorm:"type:char(32)" json:"password"`
	Phone    string `gorm:"type:char(11)" json:"phone"`
}

func (u *User) CreatUser(db *gorm.DB, phone string) error {
	return db.Where("phone=?", phone).Limit(1).Find(&u).Error
}
func (u *User) AddUser(db *gorm.DB) error {
	return db.Create(&u).Error
}
func UsernameList(db *gorm.DB, req request.UsernameList) ([]User, int64, error) {
	var user []User
	var total int64
	query := db.Where("username like ?", "%"+req.Username+"%")
	if err := query.Model(&User{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}
	if err := query.Find(&user).Error; err != nil {
		return nil, 0, err
	}
	return user, total, nil
}

type Friend struct {
	UserId   int `gorm:"type:int" json:"userId"`
	FriendId int `gorm:"type:int" json:"friendId"`
	Status   int `gorm:"not null;default 0;comment:状态 0:已申请,1:已通过"`
}

// 添加好友
func (f *Friend) AddFriend(db *gorm.DB) error {
	return db.Create(&f).Error
}

// 判断是否是好友
func (f *Friend) IsFriend(db *gorm.DB, userId int, friendId int) bool {
	var count int64
	db.Where("user_id=? and friend_id=?", userId, friendId).Count(&count)
	return count > 0
}
func (f *Friend) FriendList(db *gorm.DB, friendId int) error {
	return db.Where("friend_id", friendId).Limit(1).Find(&f).Error
}

type Blacklist struct {
	gorm.Model
	UserId    int64  `gorm:"type:int" json:"userId"`
	BlackedId int64  `gorm:"type:int" json:"BlackedId"`
	Username  string `gorm:"type:varchar(30)" json:"username"`
}

func AddBlacklist(userId int64, req request.AddBlack) error {
	var count int64
	result := config.DB.Model(&Blacklist{}).
		Where("user_id=? and blacked_id=?", userId, req.BlackedId).Count(&count)
	if result.Error != nil {
		return result.Error
	}
	if count > 0 {
		return errors.New("该用户已在黑名单中")
	}
	blacklist := &Blacklist{
		UserId:    userId,
		BlackedId: req.BlackedId,
		Username:  "流域则",
	}
	result = config.DB.Create(blacklist)
	return result.Error
}
func GetBlacklist(req request.GetBlack) ([]Blacklist, error) {
	var blacklists []Blacklist
	result := config.DB.Where("user_id=?", req.UserId).Find(&blacklists)
	return blacklists, result.Error
}

type Moment struct {
	gorm.Model
	UserId  int64  `gorm:"type:int" json:"UserId"`
	Content string `gorm:"type:varchar(30)" json:"Content"`
}
type Like struct {
	gorm.Model
	MomentId int64 `gorm:"type:int" json:"MomentId"`
	UserId   int64 `gorm:"type:int" json:"UserId"`
}
